package ys.db2es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
//类名规范点应为ElasticsearchConfig,此处证明了类的命名可一随意点
public class ES {

    @Value("${es.host}")
    private List<String> hosts;

    @Value("${es.port}")
    private List<Integer> ports;

    @Bean
//    public RestHighLevelClient restHighLevelClient() {
    public RestHighLevelClient es() {

        if (hosts.size() != ports.size()) {
            throw new RuntimeException("[连接ES] host和port数量不一致!!!");
        }
        //构建HttpHost
        HttpHost[] httpHostArray = new HttpHost[hosts.size()];
        for (int i = 0; i < hosts.size(); i++) {
            HttpHost httpHost = new HttpHost(hosts.get(i), ports.get(i));
            httpHostArray[i] = httpHost;
        }
        //创建RestClient对象
        RestClientBuilder builder = RestClient.builder(httpHostArray);
        //创建返回可以使用的连接对象
        return new RestHighLevelClient(builder);
    }

}
